package com.odin.core.controller;

import com.odin.core.dao.ResourceMapper;
import com.odin.core.dao.RoleMapper;
import com.odin.core.dao.RoleResourceMapper;
import com.odin.core.entity.Resource;
import com.odin.core.entity.Role;
import com.odin.core.entity.RoleResourceKey;
import com.odin.core.entity.User;
import com.odin.core.service.RoleService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    RoleService roleService;
    //这里直接使用rolemapper，方便操作
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    ResourceMapper resourceMapper;
    @Autowired
    RoleResourceMapper roleResourceMapper;

    @RequiresPermissions("role:getResource")
    @RequestMapping("/getResource")
    @ResponseBody
    public List<Resource> getResource(String roleId){
       return  roleService.findResourceByRole(roleId);
    }

    @RequestMapping("list")
    public String list(Model model){
        model.addAttribute("list",roleMapper.findAll());
    return "role/list";
    }
    @RequestMapping("editRoleResource")
    public String editRoleResource(String roleId,Model model){
        List<Resource> resources = resourceMapper.findAll();
        model.addAttribute("roleId",roleId);
        model.addAttribute("resources",resources);
        return "role/editResource";
    }

    @RequestMapping("saveRoleResource")
    public String saveRoleResource(String roleId, Model model, HttpServletRequest request,RedirectAttributes redirectAttributes){
        String[] resources = request.getParameterValues("resources");
        System.out.print(resources);
        //先删除所有权限
        roleResourceMapper.deleteByRole(roleId);
        if(resources!=null && resources.length!=0){
            for (String resourceId:resources) {
                RoleResourceKey roleResourceKey = new RoleResourceKey();
                roleResourceKey.setRoleId(roleId);
                roleResourceKey.setResourceId(resourceId);
                roleResourceMapper.insert(roleResourceKey);
            }
        }
        model.addAttribute("resources",resources);
        return "redirect:list";
    }

    @RequestMapping("save")
    public String save(Role role){
        role.setId(UUID.randomUUID().toString());
        roleMapper.insert(role);
        return "redirect:list";
    }
    @RequestMapping("toAdd")
    public String toAdd(){
        return "role/roleAdd";
    }


}
